package com.miaostars.myaifriend;

import com.theokanning.openai.audio.SpeechRequest;
import com.theokanning.openai.service.OpenAiService;
import org.bukkit.entity.Player;
import java.nio.file.*;
import java.util.concurrent.*;

public class VoiceManager {
    private final ConfigManager configManager;
    private final AIHandler aiHandler;
    private final ExecutorService executor = Executors.newCachedThreadPool();

    public VoiceManager(ConfigManager configManager, AIHandler aiHandler) {
        this.configManager = configManager;
        this.aiHandler = aiHandler;
    }

    // 语音处理全链路：采集→识别→AI回复→合成→播放
    public void processVoice(Player player, byte[] audioData) {
        executor.submit(() -> {
            try {
                // 1. 语音识别 (ASR)
                String text = recognizeSpeech(audioData);
                player.sendMessage("§a你说: " + text);
                
                // 2. 获取AI回复
                String aiText = aiHandler.getResponse(player, text);
                
                // 3. 语音合成 (TTS)
                byte[] audioBytes = synthesizeSpeech(aiText);
                Path path = Paths.get("plugins/MyAIFriend/audio/" + player.getName() + ".mp3");
                Files.write(path, audioBytes);
                
                // 4. 播放语音
                new AudioPlayer(player).play(path);
            } catch (Exception e) {
                player.sendMessage("§c语音处理失败: " + e.getMessage());
            }
        });
    }

    private String recognizeSpeech(byte[] audioData) {
        OpenAiService service = new OpenAiService(configManager.getConfig().getString("openai_api_key"));
        return service.createTranscription(audioData, "voice.wav").getText();
    }

    private byte[] synthesizeSpeech(String text) {
        OpenAiService service = new OpenAiService(configManager.getConfig().getString("openai_api_key"));
        SpeechRequest request = SpeechRequest.builder()
            .model(configManager.getConfig().getString("tts_model", "tts-1"))
            .voice(configManager.getConfig().getString("ai_voice", "nova"))
            .input(text)
            .build();
        return service.createSpeech(request).getBytes();
    }

    public void reloadConfig() { configManager.reloadConfig(); }
    public void shutdown() { executor.shutdown(); }
}